<template>
	<s-layout title="新增地址" class="add-wrap">
		<view class="container">
			<view class="card my-4 p-4">
				<uni-forms
					class="form-box"
				  ref="addressFormRef"
				  v-model="state.model"
				  :rules="state.rules"
				  validateTrigger="bind"
				  labelWidth="150"
				  labelAlign="left"
				>
					<view class="form-item">
						<uni-forms-item name="consignee" label="姓名">
							<uni-easyinput
								v-model="state.model.consignee"
								:inputBorder="false"
								placeholder="请输入姓名"
							/>
						</uni-forms-item>
					</view>
					<view class="form-item">
						<uni-forms-item name="mobile" :label="phoneLabel">
							<view class="ss-flex">
								<view class="ss-flex-1">
									<uni-easyinput
										v-model="state.model.mobile"
										type="number"
										:inputBorder="false"
										v-show="phoneType"
										placeholder="请输入电话"
									/>
									<view class="ss-flex" v-show="!phoneType">
										<uni-easyinput
											v-model="state.model.code"
											type="number"
											:inputBorder="false"
											placeholder="请输入区号"
										/>
										<text>-</text>
										<uni-easyinput
											v-model="state.model.landline"
											type="number"
											:inputBorder="false"
											placeholder="请输入座机号"
										/>
									</view>
								</view>
								<view class="change" @tap="phoneType = !phoneType">
									{{ phoneType ? '切换固话': '切换手机' }}
								</view>
							</view>
						</uni-forms-item>
					</view>
					<view class="address">
						<view class="info">
							<view class="form-item">
								<uni-forms-item name="region" label="省市区">
									<view class="value" @tap="visible = true">
										<uni-easyinput
											v-model="state.model.region"
											disabled
											:styles="{
												disableColor: '#fff',
												color: '#333'
											}"
											placeholderStyle="color:#BBBBBB;font-size:28rpx;font-weight:400;line-height:normal"
											:inputBorder="false"
											placeholder="请选择省市区"
										/>
									</view>
								</uni-forms-item>
							</view>
							<view class="form-item">
								<uni-forms-item name="address" label="详细地址">
									<uni-easyinput
										v-model="state.model.address"
										type="textarea"
										class="ss-flex-1"
										:inputBorder="false"
										placeholder="请输入详细地址"
									/>
								</uni-forms-item>
							</view>
						</view>
						<view class="locate" @tap="authVerification">
							<image class="icon" src="/static/index/icon-locate.png"></image>
							定位
						</view>
					</view>
					<view class="clear" @tap="onClear">清空地址</view>
				</uni-forms>
			</view>
			<view class="card my-4 p-4 pb-5 identify">
				<view class="ss-flex ss-row-between mb-4">
					<view class="title">
						智能识别
					</view>
					<view class="ss-flex operate">
						<view class="btn" @tap="onAnalysis">
							识别
						</view>
						<view class="btn" @tap="state.content = ''">
							清空
						</view>
					</view>
				</view>
				<view class="textarea">
					<textarea v-model.trim="state.content" placeholder="粘贴或者输入完整地址, 点击识别将自动为您填入地址"></textarea>
				</view>
			</view>
		</view>
		<view class="fixed">
			<button class="button" @tap="onSave">
				确定
			</button>
		</view>
		<!-- 省市区弹窗 -->
		<su-region-picker
		  :show="visible"
		  @cancel="visible = false"
		  @confirm="onRegionConfirm"
		/>
	</s-layout>
</template>

<script setup>
	import { ref, reactive, computed, unref, watch, onBeforeMount } from 'vue'
	import sheep from '@/sheep';
  import { onLoad } from '@dcloudio/uni-app';
	import { consignee, mobile, address, region, landline } from '@/sheep/validate/form';
	
	let current = 1
	const phoneType = ref(true)
	const visible = ref(false)
  const addressFormRef = ref(null);
	const state = reactive({
		content: '',
		model: {
			consignee: '',
			mobile: '',
			address: '',
			region: '',
			landline: '',
			code: ''
		},
		rules: {
		  consignee,
		  mobile,
		  address,
		  region,
		}
	})
	const phoneLabel = computed(() => {
		return phoneType.value ? '手机' : '固话'
	})
	watch(
		phoneType,
		(newValue) => {
			state.rules.mobile = newValue ? mobile : landline
		}
	)
	watch(
	  () => state.model.province_name,
	  (newValue) => {
	    if (newValue) {
	      state.model.region = `${state.model.province_name}-${state.model.city_name}-${state.model.district_name}`;
	    }
	  },
	  {
	    deep: true,
	  },
	);
	const onRegionConfirm = (e) => {
		state.model = {
		  ...state.model,
		  ...e,
		};
	  visible.value = false;
	};
	
	const onSave = async () => {
	  const validate = await unref(addressFormRef)
	    .validate()
	    .catch((error) => {
	      console.log('error: ', error);
	    });
	  if (!validate) return;
	
	  let res = null;
		let { code, landline, ...params } = state.model
		if (!phoneType.value) {
			if (code && landline) {
				params.mobile = code + '-' + landline
			} else {
				uni.showToast({
				  title: '请输入固话号码',
				  icon: 'none',
				});
				return
			}
		}
	  if (params.id) {
	    res = await sheep.$api.user.address.update(params.id, params);
	  } else {
	    res = await sheep.$api.user.address.create(params, current);
	  }
	  if (res.code === 1) {
	    sheep.$router.back();
	  }
	};
	
	const onAnalysis = async () => {
		if (state.content) {
			const { data, code } = await sheep.$api.mail.analysis(state.content);
			if (code == 1) {
				state.model = {
					consignee: data.person,
					mobile: data.phonenum,
					address: data.town + data.detail,
					region: `${data.province}-${data.city}-${data.county}`,
					city_id: data.city_code,
					city_name: data.city,
					district_id: data.county_code,
					district_name: data.county,
					province_id: data.province_code,
					province_name: data.province,
				}
			}
		} else {
			uni.showToast({
			  title: '请输入完整地址',
			  icon: 'none',
			});
		}
	}
		
	const onClear = () => {
		state.model = {
			consignee: '',
			mobile: '',
			address: '',
			region: '',
			landline: '',
			code: ''
		}
	}
	
	function handerChooseLocation (latitude, longitude) {
		uni.chooseLocation({
			latitude: latitude || '',
			longitude: longitude || '',
			async success(res) {
				const { data, code } = await sheep.$api.mail.analysis(res.address);
				if (code == 1) {
					let value = {
						consignee: state.model.consignee,
						mobile: state.model.mobile,
						landline: state.model.landline,
						code: state.model.code,
						address: data.town + data.detail,
						region: `${data.province}-${data.city}-${data.county}`,
						city_id: data.city_code,
						city_name: data.city,
						district_id: data.county_code,
						district_name: data.county,
						province_id: data.province_code,
						province_name: data.province,
					}
					state.model = value
				}
			},
			fail(err) {
				console.log('取消按钮', err);
			}
		})
	}
	
	function handleOpenSetting () {
		wx.openSetting({
			success(res) {
				if (res.authSetting['scope.userLocation']) {
					handerChooseLocation()
				}
			}
		})
	}
	
	const authVerification = () => {
		uni.getSetting({
			success(res) {
				if (res.authSetting['scope.userLocation']) {
					handerChooseLocation()
				} else {
					handleOpenSetting()
				}
			}
		})
	}
	
	onLoad(async (option) => {
		current = option.type - 0
		
		if (option.id) {
		  let res = await sheep.$api.user.address.detail(option.id);
		  if (res.code === 1) {
				if (res.data.mobile.indexOf('-') > -1) {
					phoneType.value = false
					const arr = res.data.mobile.split('-')
					state.model.code = arr[0]
					state.model.landline = arr[1]
					res.data.mobile = ''
				}
		    state.model = {
		      ...state.model,
		      ...res.data,
		    };
		  }
		}
	})
	
	onBeforeMount(() => {
	  if (!!uni.getStorageSync('areaData')) {
	    return;
	  }

	  // 提前加载省市区数据
	  sheep.$api.data.area().then((res) => {
	    if (res.code === 1) {
	      uni.setStorageSync('areaData', res.data);
	    }
	  });
	});
</script>

<style lang="scss" scoped>
	.container {
		width: 92%;
		margin: 0 auto;
		padding-bottom: 148rpx;
	}
	.form-box {
		.form-item {
			position: relative;
			// display: flex;
			// align-items: center;
			// padding: 30rpx 0;
			// color: #000000;
			// font-size: 30rpx;
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				width: 100%;
				border-bottom: 2rpx solid #eee;
			}
			input {
				width: 360rpx;
			}
			.telephone {
				width: 350rpx;
				input {
					width: 155rpx;
				}
			}
			.change {
				color: #0396ff;
			}
		}
		.address {
			display: flex;
			.info {
				width: 80%;
				.ss-flex-1 {
					height: 200rpx;
				}
			}
			.locate {
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				border-bottom: 2rpx solid #eee;
				border-left: 2rpx solid #eee;
				width: 20%;
				row-gap: 10rpx;
				.icon {
					width: 44rpx;
					height: 44rpx;
				}
			}
		}
		.clear {
			text-align: right;
			color: #989898;
			margin-top: 20rpx;
		}
	}
	.identify {
		font-size: 32rpx;
		.title {
			color: #000000;
			font-weight: 600;
		}
		.operate {
			column-gap: 20rpx;
			.btn {
				width: 100rpx;
				height: 46rpx;
				line-height: 46rpx;
				text-align: center;
				color: #0396ff;
				font-weight: 600;
				border: 2rpx solid #0396ff;
				border-radius: 46rpx;
			}
		}
		.textarea {
			padding: 20rpx;
			background-color: #f5f5f5;
			border-radius: 30rpx;
			height: 160rpx;
		}
	}
	.fixed {
		position: fixed;
		width: 100%;
		bottom: 0;
		padding: 30rpx;
		background-color: #fff;
		box-sizing: border-box;
		z-index: 10;
		.button {
			height: 88rpx;
			line-height: 88rpx;
			font-size: 36rpx;
			color: #fff;
			border-radius: 88rpx;
			background-color: #0396ff;
			outline: none;
			border: none;
		}
	}
	:deep(.uni-easyinput) {
		.is-disabled {
			color: #333;
		}
	}
</style>